/*
 * Copyright © Yan Zhenjie
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.olc.railing.camera;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.ImageFormat;
import android.graphics.Matrix;
import android.graphics.Rect;
import android.graphics.YuvImage;
import android.hardware.Camera;
import android.text.TextUtils;
import android.util.Log;
import com.olc.railing.base.BaseApplication;
import com.olc.railing.utils.CommUtils;
import com.olc.railing.utils.MyLog;

import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import pr.platerecognization.OcrBusiness;
import pr.platerecognization.PlateInfo;

/**
 * Created by Yan Zhenjie on 2017/5/5.
 */
public class CameraScanAnalysis {

    private ExecutorService executorService = Executors.newSingleThreadExecutor();
    private ScanCallback mCallback;
    private boolean allowAnalysis = true;

    public void setScanCallback(ScanCallback callback) {
        this.mCallback = callback;
    }

    public void onStop() {
        this.allowAnalysis = false;
    }

    public void onStart() {
        this.allowAnalysis = true;
    }

    public void startScan(byte[] data, Camera camera) {
        if (allowAnalysis) {
           // Log.e("MiniCamerActivity","startScan"+ByteUtil.byte2HexStr(data));
            allowAnalysis = false;
            executorService.execute(new MyRunnable(data,camera));
        }
    }
    private List<String> list = new ArrayList<>();
    private Map<String, Integer> map = new HashMap<>();
    private class  MyRunnable implements Runnable{
        private byte[] data;
        private Camera camera;

        public MyRunnable(byte[] data, Camera camera) {
            this.data = data;
            this.camera = camera;
        }

        @Override
        public void run() {
            //Log.e("MiniCamerActivity", "result:" + result);
            //处理data
            PlateInfo result = getPlateInfo();
            MyLog.e(MyLog.TAG, "onPreviewFrame: " + result.plateName );
            if (result != null && !TextUtils.isEmpty(result.getPlateName()) && CommUtils.isCarNum(result.getPlateName())) {
                if (list.size() <= 8) {
                    list.add(result.getPlateName());
                    allowAnalysis = true;
                    return;
                }
                allowAnalysis = false;
                //重复的加入list2集合
                for (int i = 0; i < list.size(); i++) {
                    int count = 0;
                    for (int j = 0; j < list.size(); j++) {
                        if (list.get(i).equals(list.get(j))) {
                            count++;
                        }
                    }
                    map.put(list.get(i), count);
                }
                // 将这个map转换成list以便排序
                List<Map.Entry<String, Integer>> list = new ArrayList<>(map.entrySet());
                Collections.sort(list, new Comparator<Map.Entry<String, Integer>>() {
                    // 默认的是从小到大排序，
                    @Override
                    public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) {
                        // 从大到小排序
                        // return (o2.getValue() - o1.getValue());
                        // 从小到大排序
                        return (o1.getValue() - o2.getValue());
                    }
                });
              //  Log.e("111111111", "onPreviewFrame size : " + list.size());
                if (list != null && list.size() > 0) {
                    if (mCallback != null) {
                      //  Log.e("111111111", "onPreviewFrame final : " + list.get(list.size() - 1).getKey());
                        mCallback.onScanResult(list.get(list.size() - 1).getKey());
                    }
                }

            }else{
                allowAnalysis = true;
            }

        }

        private PlateInfo getPlateInfo() {

           // Camera.Size previewSize = camera.getParameters().getPreviewSize();
            BitmapFactory.Options newOpts = new BitmapFactory.Options();
            newOpts.inJustDecodeBounds = true;
            YuvImage yuvimage = new YuvImage(
                    data,
                    ImageFormat.NV21,
                    1280,
                    720,
                    null);
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            yuvimage.compressToJpeg(new Rect(0, 0, 1280, 720), 100, baos);
            byte[] rawImage = baos.toByteArray();
            //将rawImage转换成bitmap
            BitmapFactory.Options options = new BitmapFactory.Options();
            options.inPreferredConfig = Bitmap.Config.RGB_565;
            Bitmap bitmap = BitmapFactory.decodeByteArray(rawImage, 0, rawImage.length, options);
            PlateInfo result = OcrBusiness.getInstance(BaseApplication.getApplication()).SimpleRecog(rotateBitmap(bitmap), 8);
            bitmap.recycle();
            return result;
        }
    }

    private Bitmap rotateBitmap(Bitmap bmp){
        Matrix matrix = new Matrix();
        matrix.postRotate(0);
        Bitmap rotatedBitMap = Bitmap.createBitmap(bmp, 0, 0, bmp.getWidth(), bmp.getHeight(), matrix, true);
        return rotatedBitMap;
    }
}